package com.heima.admin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.heima.admin.config.BaiduAuthConfig;
import com.heima.admin.config.CacheConfig;
import com.heima.utils.baidu.Base64Util;
import com.heima.utils.baidu.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.net.URLEncoder;
/**
 * 百度云身份证识别业务
 * @author yangkexuan
 * @className AuthBaiduScanServiceImpl
 * @date 2023/8/3 10:21
 * @description
 */
@Service
@Slf4j
public class AuthBaiduScanServiceImpl {

    @Autowired
    private BaiduAuthConfig baiduConfig;

    @Autowired
    private CacheConfig cacheConfig;

    /**
     * 获取百度云token
     * @return
     */
    @Scheduled(cron = "10 * * * * ?")
    @PostConstruct
    private String refreshToken() {
        try {
            OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "");
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/oauth/2.0/token?client_id=" + baiduConfig.getApiKey()
                            + "&client_secret=" + baiduConfig.getApiSecret() + "&grant_type=client_credentials")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            String token = response.body().string();
            token = JSONObject.parseObject(token).getString("access_token");
            log.info("已获取百度云身份证识别AT");
            cacheConfig.add("token", token);
            return token;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 百度云身份证解析
     * @param imgData 图片对应的字节数据
     * @return
     */
    public String idCardSide(byte[] imgData, String picture) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
        String result = null;
        try {
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
            String param = "id_card_side=" + picture + "&image=" + imgParam;

            String accessToken = cacheConfig.get("token");

            if (StringUtils.isBlank(accessToken)) {
                accessToken = refreshToken();
            }

            result = HttpUtil.post(url, accessToken, param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
